package route

import (
	"fmt"
	"gitee.com/xluomo945/fm/mini"
	"github.com/gin-gonic/gin"
	"net/http"
	"reflect"
	"runtime"
)

type register interface {
	create(string, string, string, gin.HandlerFunc)
	base() string
}

func (r *route) create(relativePath string, method string, handlerName string, handler gin.HandlerFunc) {
	switch method {
	case http.MethodGet:
		r.engine.GET(relativePath, handler)
	case http.MethodPost:
		r.engine.POST(relativePath, handler)
	case http.MethodPut:
		r.engine.PUT(relativePath, handler)
	case http.MethodPatch:
		r.engine.PATCH(relativePath, handler)
	case http.MethodDelete:
		r.engine.DELETE(relativePath, handler)
	case http.MethodOptions:
		r.engine.OPTIONS(relativePath, handler)
	case http.MethodHead:
		r.engine.HEAD(relativePath, handler)
	default:
		// 没有提供的注册方法, 按照Any直接注册一个梭哈
		r.engine.Any(relativePath, handler)
	}
	fmt.Println(fmt.Sprintf("| %-8s | %-35s | %-75s |", method, fmt.Sprintf("%s/%s", r.engine.BasePath(), relativePath), handlerName))
}

func (r *route) base() string {
	return r.engine.BasePath()
}

func create[T any, S any](r register, relativePath string, method string, fn handler[T, S]) {
	mini.AppendRoute(&mini.ApiDocs{
		Route:  fmt.Sprintf("%s/%s", r.base(), relativePath),
		Method: method,
	}, reflect.TypeOf((*T)(nil)).Elem(), reflect.TypeOf((*S)(nil)).Elem())
	r.create(relativePath, method, runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name(), process(fn))
}
